<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="缴费类型" prop="paymentType" >
        <el-select v-model="queryParams.paymentType"  style="width: 160px"  placeholder="请选择缴费类型" clearable>
          <el-option label="水费" value="0"></el-option>
          <el-option label="电费" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="缴费金额" prop="paymentPrice">
        <el-input
            v-model="queryParams.paymentPrice"
            placeholder="请输入缴费金额"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="缴费方式" prop="paymentWay" >
        <el-select v-model="queryParams.paymentWay" placeholder="请选择缴费方式" clearable  style="width: 150px">
          <el-option label="支付宝" value="支付宝"></el-option>
          <el-option label="微信" value="微信"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="缴费时间" prop="paymentTime">
        <el-date-picker clearable
                        v-model="queryParams.paymentTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择缴费时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="primary"-->
<!--            plain-->
<!--            icon="Plus"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['paymentUser:payUser:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="Edit"-->
<!--            :disabled="single"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['paymentUser:payUser:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="Delete"-->
<!--            :disabled="multiple"-->
<!--            @click="handleDelete"-->
<!--            v-hasPermi="['paymentUser:payUser:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="Download"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['paymentUser:payUser:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="payUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="缴费类型" align="center" prop="paymentType">
        <template #default="scope">
          <span>{{ scope.row.paymentType === 0 ? '水费' : '电费' }}</span>
        </template>
      </el-table-column>

<!--      <el-table-column label="缴费业主ID" align="center" prop="paymentUser" />-->
      <el-table-column label="缴费方式" align="center" prop="paymentWay" />
      <el-table-column label="缴费金额" align="center" prop="paymentPrice" />
      <el-table-column label="缴费时间" align="center" prop="paymentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缴费状态" align="center" prop="paymentStatus">
        <template #default="scope">
          <el-tag :type="scope.row.paymentStatus === 0 ? 'warning' : 'success'">
            {{ scope.row.paymentStatus === 0 ? '待缴费' : '已缴费' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="paymentDetail" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['paymentUser:payUser:edit']">修改</el-button>-->
<!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['paymentUser:payUser:remove']">删除</el-button>-->
          <el-button link type="success" icon="Wallet" @click="handlePay(scope.row)" v-if="scope.row.paymentStatus === 0">去支付</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改缴费对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="payUserRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="缴费金额" prop="paymentPrice">
          <el-input v-model="form.paymentPrice" placeholder="请输入缴费金额" />
        </el-form-item>
<!--        <el-form-item label="缴费业主ID" prop="paymentUser">-->
<!--          <el-input v-model="form.paymentUser" placeholder="请输入缴费业主ID" />-->
<!--        </el-form-item>-->

        <el-form-item label="缴费类型" prop="paymentType">
          <el-select v-model="form.paymentType" placeholder="请选择缴费类型">
            <el-option label="水费" value=0></el-option>
            <el-option label="电费" value=1></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="缴费方式" prop="paymentWay">
          <el-input v-model="form.paymentWay" placeholder="请输入缴费方式" />
        </el-form-item>
        <el-form-item label="缴费时间" prop="paymentTime">
          <el-date-picker clearable
                          v-model="form.paymentTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择缴费时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="缴费详情" prop="paymentDetail">
          <el-input v-model="form.paymentDetail" placeholder="请输入缴费详情" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PayUser">
import { listPayUser, getPayUser, delPayUser, addPayUser, updatePayUser } from "@/api/paymentUser/payUser"
// 引入request用于发送支付请求
import request from '@/utils/request'

const { proxy } = getCurrentInstance()

const payUserList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 存储订单的uniqueCode映射
const orderCodeMap = new Map()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    paymentType: null,
    paymentPrice: null,
    paymentUser: null,
    paymentWay: null,
    paymentTime: null,
    paymentStatus: null,
    paymentDetail: null
  },
  rules: {
    paymentType: [
      { required: true, message: "缴费类型不能为空", trigger: "change" }
    ],
    paymentPrice: [
      { required: true, message: "缴费金额不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询缴费列表 */
function getList() {
  loading.value = true
  listPayUser(queryParams.value).then(response => {
    payUserList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    paymentType: null,
    paymentPrice: null,
    paymentUser: null,
    paymentWay: null,
    paymentTime: null,
    paymentStatus: null,
    paymentDetail: null
  }
  proxy.resetForm("payUserRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加缴费"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPayUser(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改缴费"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["payUserRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePayUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPayUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除缴费编号为"' + _ids + '"的数据项？').then(function() {
    return delPayUser(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('paymentUser/payUser/export', {
    ...queryParams.value
  }, `payUser_${new Date().getTime()}.xlsx`)
}

// 去支付 - 支付按钮操作
function handlePay(row) {
  let uniqueCode = orderCodeMap.get(row.id)

  // 如果该订单还没有生成uniqueCode，则生成一个新的并保存
  if (!uniqueCode) {
    // 根据订单ID生成唯一的uniqueCode
    uniqueCode = btoa(row.id.toString()).replace(/[^a-zA-Z0-9]/g, '').substr(0, 16)
    // 如果转换后的字符串不足16位，则在末尾补随机字符
    if (uniqueCode.length < 16) {
      const randomPart = Math.random().toString(36).substr(2, 16 - uniqueCode.length)
      uniqueCode += randomPart
    }
    // 保存该订单的uniqueCode
    orderCodeMap.set(row.id, uniqueCode)
  }

  // 去支付 - 构造支付请求参数
  const payRequest = {
    orderId: row.id,
    uniqueCode: uniqueCode
  }

  // 去支付 - 发送支付请求
  request({
    url: '/payment/pay/payZfb',
    method: 'post',
    data: payRequest,
    responseType: 'text'
  }).then(response => {
    // 去支付 - 创建临时页面并提交表单跳转到支付宝（新窗口打开）
    const newWindow = window.open('', '_blank')
    if (newWindow) {
      newWindow.document.write(response)
      newWindow.document.close()
    } else {
      // 如果无法打开新窗口，则在当前窗口打开
      document.write(response)
      document.close()
    }
  }).catch((error) => {
    proxy.$modal.msgError("支付请求失败")
  })
}

getList()
</script>
